package com.GlobalPaint.app.ui.Login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.GlobalPaint.app.Base.BaseActivity;
import com.GlobalPaint.app.R;
import com.GlobalPaint.app.bean.LogBean;
import com.GlobalPaint.app.bean.ReturnStatusResultEntity;
import com.GlobalPaint.app.bean.codeBean;
import com.GlobalPaint.app.ui.MainActivity;
import com.GlobalPaint.app.ui.Register.Register;
import com.GlobalPaint.app.utils.CommUtility;
import com.GlobalPaint.app.utils.Constants;
import com.GlobalPaint.app.utils.DataManager;
import com.blankj.utilcode.utils.SPUtils;
import com.google.gson.Gson;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.GlobalPaint.app.R.id.lg_et_phone_code;

public class Login extends BaseActivity {
    public static boolean loginFailed = false;
    @BindView(R.id.lg_img_delete)
    ImageView lgImgDelete;
    @BindView(R.id.btn_password)
    Button btnPassword;
    @BindView(R.id.qiehuan)
    ImageView qiehuan;
    @BindView(R.id.ll_password)
    LinearLayout llPassword;
    @BindView(lg_et_phone_code)
    EditText lgEtPhoneCode;
    @BindView(R.id.lg_img_delete_code)
    ImageView lgImgDeleteCode;
    @BindView(R.id.lg_et_password_code)
    EditText lgEtPasswordCode;
    @BindView(R.id.lg_img_password_eye_code)
    ImageView lgImgPasswordEyeCode;
    @BindView(R.id.ll_code)
    LinearLayout llCode;
    @BindView(R.id.tv_code)
    TextView tvCode;
    private SPUtils spUtils;
    @BindView(R.id.lg_et_phone)
    EditText lgEtPhone;
    @BindView(R.id.lg_et_password)
    EditText lgEtPassword;
    @BindView(R.id.lg_img_password_eye)
    ImageView lgImgPasswordEye;
    @BindView(R.id.btn_log)
    Button btnLog;
    @BindView(R.id.btn_zhuce)
    Button btnZhuce;
    private codeBean codebean;
    private LogBean logBean;
    private String code;
    private boolean qiehuan1 = true;//如果是true为密码登录 否则验证码登入
    private long mBackPressedTime;
    private boolean isDisplayPassword;//是否显示密码
    public static final int CMD_USER_LOGIN = 0X0006;
    public static final int CMD_USER_LOGIN_CODE = 0X0007;
    public static final int CMD_CODE = 0X0001;
    int recLen = 0;
    int total = 60;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            recLen++;
            int remain = total - recLen;
            if (remain == 0) {
                recLen = 0;
                tvCode.setText("重新发送");
                tvCode.setEnabled(true);
                return;
            } else {
                tvCode.setEnabled(false);
                String display = String.valueOf(remain) + "秒后重发";
                tvCode.setText(display);
            }
            handler.postDelayed(this, 1000);
        }
    };
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case CMD_USER_LOGIN:
                    spUtils.putString("user", "123456");
                    spUtils.putString("mobile", String.valueOf(lgEtPhone.getText()));
                    loginFailed = false;
                    // 前往绑定或者注册操作
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case CMD_USER_LOGIN_CODE:
                    String urllog= Constants.JASON_SERVICE_URL+"/renren-security/appapi/user/loginByCode?fUsername="
                            +String.valueOf(lgEtPhoneCode.getText())+"&verificationCode"+code;
                    DataManager.getInst().getHttpRequestJsonClass(urllog, "dd", LogBean.class, new DataManager.Callback() {
                        @Override
                        public void onSuccess(Object o) {
                            logBean=(LogBean)o;
                            DataManager.userEntity = logBean.getData();
//                                    DataManager.curHouseTO = CommUtility.getDefaultHoustTO(DataManager.userEntity.houses);
                            spUtils.putString("user", new Gson().toJson(logBean.getData()));
                            spUtils.putString("mobile", String.valueOf(lgEtPhoneCode.getText()));
                            loginFailed = false;
                            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                            startActivity(intent);
                            finish();
                        }

                        @Override
                        public void onFailure(ReturnStatusResultEntity error) {

                        }
                    });
                    break;
                case CMD_CODE:
                    String url= Constants.JASON_SERVICE_URL+"/renren-security/appapi/user/sendSms?type=1&phone="
                            +String.valueOf(lgEtPhoneCode.getText());
                    DataManager.getInst().getHttpRequestJsonClass(url, "dd", codeBean.class, new DataManager.Callback() {
                        @Override
                        public void onSuccess(Object o) {
                            codebean=(codeBean)o;
                        }

                        @Override
                        public void onFailure(ReturnStatusResultEntity error) {
                            Toast.makeText(Login.this,"获取验证码失败请稍后再试",Toast.LENGTH_LONG).show();
                        }
                    });
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        //判断是否有账号密码
        spUtils = new SPUtils(DataManager.context, "login");
        String mobile = spUtils.getString("mobile");
        lgEtPhone.setText(mobile);
        if (!loginFailed) {
            String user = spUtils.getString("user");
            if (!TextUtils.isEmpty(user) && !user.equals("null")) {
                   DataManager.userEntity = new Gson().fromJson(user, LogBean.DataBean.class);
                //当登录一次退出后,下一次直接进入主界面
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
                finish();
                loginFailed = false;
            }
        }
    }

    private void displayPassword() {
        CommUtility.displayPassword(lgEtPassword, lgImgPasswordEye, isDisplayPassword);
        isDisplayPassword = !isDisplayPassword;
    }

    @OnClick({R.id.btn_log, R.id.btn_zhuce, R.id.lg_img_password_eye, R.id.lg_img_delete,R.id.tv_code,
            R.id.btn_password, R.id.qiehuan, R.id.lg_img_delete_code, R.id.lg_img_password_eye_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_code:
                if (TextUtils.isEmpty(lgEtPhoneCode.getText())) {
                    Toast.makeText(Login.this, "请输入账号", Toast.LENGTH_SHORT).show();
                    return;
                }
                runnable.run();
                mHandler.sendEmptyMessage(CMD_CODE);
                break;
            case R.id.btn_log:

                login();
                break;
            case R.id.btn_zhuce:
                Intent intent = new Intent(Login.this, Register.class);
                startActivity(intent);
                break;
            case R.id.lg_img_password_eye:

            case R.id.lg_img_password_eye_code:
                displayPassword();
                break;
            case R.id.lg_img_delete_code:

            case R.id.lg_img_delete:
                lgEtPhone.setText("");
                break;
            case R.id.btn_password:

                break;
            case R.id.qiehuan:
                qiehuan1 = !qiehuan1;
                if (qiehuan1 == true) {
                    llCode.setVisibility(View.GONE);
                    llPassword.setVisibility(View.VISIBLE);
                } else {
                    llPassword.setVisibility(View.GONE);
                    llCode.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    private void login() {
        if (qiehuan1 == true) { //账号密码登录
            if(CommUtility.checkValidate(this,lgEtPhone.getText().toString())){
            }else {
                return;
            }
            if (TextUtils.isEmpty(lgEtPassword.getText())) {
                Toast.makeText(Login.this, "请输入密码", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.equals(lgEtPhone.getText(), "123456")) {
                spUtils.putString("user", "123456");
                spUtils.putString("mobile", String.valueOf(lgEtPhone.getText()));
                loginFailed = false;
                Intent intent = new Intent(Login.this, MainActivity.class);
                startActivity(intent);
                finish();
                return;
            } else {
                Toast.makeText(Login.this, "登录失败", Toast.LENGTH_SHORT).show();
            }
            mHandler.sendEmptyMessage(CMD_USER_LOGIN);
        } else {
            if(CommUtility.checkValidate(this,lgEtPhoneCode.getText().toString())){

            }else {
                return;
            }
            code=tvCode.getText().toString();
            if (TextUtils.isEmpty(code)) {
                Toast.makeText(Login.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                return;
            }

            mHandler.sendEmptyMessage(CMD_USER_LOGIN_CODE);
        }

    }

    @Override
    public void onBackPressed() {

        boolean isDoubleClick = true;// BaseApplication.get(AppConfig.KEY_DOUBLE_CLICK_EXIT, true);

        if (isDoubleClick) {
            long curTime = SystemClock.uptimeMillis();
            if ((curTime - mBackPressedTime) < (3 * 1000)) {
                finish();
            } else {
                mBackPressedTime = curTime;
                Toast.makeText(this, "再次点击退出", Toast.LENGTH_LONG).show();
            }
        } else {
            finish();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (CommUtility.isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }


}
